﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Collections.ObjectModel;
using _18miljard.Db;
using _18miljard.Mail;

namespace _18miljard.Daily
{
	internal class JobScheduler
	{
		Collection<DailyJob> jobs = new Collection<DailyJob>();
		DateTime today = DateTime.Today;

		internal JobScheduler()
		{
			XmlDocument doc = new XmlDocument();
			doc.Load(HttpContext.Current.Server.MapPath("/App_Data/Scheduler.xml"));

			foreach (XmlNode jobNode in doc.DocumentElement.ChildNodes)
			{
				if (jobNode.NodeType == XmlNodeType.Comment)
					continue;
				string freq = jobNode.Attributes["frequency"].Value;

				switch (freq)
				{
					case "daily": this.HandleDaily(jobNode); break;
					case "weekly": this.HandleWeekly(jobNode); break;
					case "monthly": this.HandleMonthly(jobNode); break;
					case "yearly": this.HandleYearly(jobNode); break;
				}
			}
		}

		internal void Execute()
		{
			QueryCollection updateQueries = new QueryCollection();
			BulkEMail emails = new BulkEMail();

			Global.BlockMail();

			foreach (DailyJob job in this.jobs)
			{
				job.Execute();

				updateQueries.Add(job.Queries);
				emails.Add(job.Emails);
			}

			LogWriter.Write("Executing queries...");

			//With 18miljard, I don't have a db so no queries. I do have mails though, so leave the code.
			updateQueries.Execute();

			emails.Send(true);

			Global.ReleaseMail();
		}

		private void HandleDaily(XmlNode node)
		{
			this.AddJob(node);
		}

		private void HandleWeekly(XmlNode node)
		{
			if ((int)today.DayOfWeek == XmlConvert.ToInt32(node.Attributes["weekday"].Value))
				this.AddJob(node);
		}

		private void HandleMonthly(XmlNode node)
		{
			if (today.Day == XmlConvert.ToInt32(node.Attributes["dayofmonth"].Value))
				this.AddJob(node);
		}

		private void HandleYearly(XmlNode node)
		{
			if (today.Day == XmlConvert.ToInt32(node.Attributes["day"].Value)
				&& today.Month == XmlConvert.ToInt32(node.Attributes["month"].Value))
					this.AddJob(node);
		}

		private void AddJob(XmlNode node)
		{
			this.jobs.Add( (DailyJob)Activator.CreateInstance(Type.GetType("_18miljard.Daily." + node.Attributes["class"].Value), node) );
		}
	}
}